package com.overoid.diary.ui.day.edit;

import java.util.HashMap;
import java.util.Iterator;

import com.overoid.diary.R;
import com.overoid.diary.ui.DayActivity;
import com.overoid.diary.ui.common.ActivityImpl;
import com.overoid.diary.ui.common.Constants;
import com.overoid.diary.ui.common.DBHelper;

import android.app.LocalActivityManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class DayEditActivity extends ActivityImpl {
	
	
	public LocalActivityManager mLocalActivityManager = new LocalActivityManager(this, true);
	protected DayEditActivity parentActivity ;
	protected int tabIdx = 0; ;
	
	protected Window wTop01;
	protected Window wTop02;
	protected Window wBottom01;
	protected Window wBottom02;
	
	protected DBHelper db;
	
	// local device picture view
	protected int totalImgCnt=0;
	protected int curentImgPositon=0;
	
	// database photo top  picture 
	protected int dayImgCnt=0;			// 전체 이미지 갯수
	protected int selectImgCnt=0; // 선택된 저장된 이미지
	protected HashMap<Integer ,ImageButton> top2DayImgsMap = new HashMap<Integer,ImageButton>();  // top2 image object
	
	// 저장할 category id
	protected int categotyID = 0;
	
	// 저장할 category may : 순서대로 넣은후
	//protected HashMap<Integer ,ArrayList<Integer>> categoryMap = new HashMap<Integer,ArrayList<Integer>>();  // top2 image object
	
	// 현재 memo id 없으면 0
	protected int memoID = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);	
		
		setContentView(R.layout.day_edit);
		
		//
		memoID = getIntent().getIntExtra("memo_id",0);
		
		if(memoID == 0){
			 ((TextView)findViewById(R.id.dayEditTxtTitle)).setText("New Memo");
		}else{
			((TextView)findViewById(R.id.dayEditTxtTitle)).setText("Edit Memo");
		}
		
		
		parentActivity=this;
		
		//database
		db = new DBHelper(getApplicationContext());
		        
		FrameLayout topFrameContent 	= (FrameLayout) findViewById(R.id.dayEditFrameTop);
		FrameLayout bottomFrameContent 	= (FrameLayout) findViewById(R.id.dayEditFrameBottom);
		
		// 이걸 해줘야 mLocalActivityManager 를 쓸수 있음...
		Bundle states = savedInstanceState != null ? (Bundle) savedInstanceState.getBundle("android:states") : null;
        mLocalActivityManager.dispatchCreate(states);
		 
		wTop01 = mLocalActivityManager.startActivity( "wTop01", new Intent(this,DayEditViewTop01Activity.class));
		wTop02 = mLocalActivityManager.startActivity( "wTop02", new Intent(this,DayEditViewTop02Activity.class));
		
		wBottom01 = mLocalActivityManager.startActivity( "wBottom01", new Intent(this,DayEditViewBottom01Activity.class));
		// category setting
		DayEditViewBottom01Activity bottom01Act = (DayEditViewBottom01Activity)mLocalActivityManager.getActivity("wBottom01");
		
		ImageButton imgCategory =null;
		
		if(categotyID ==1 ){
			imgCategory = (ImageButton)bottom01Act.findViewById(R.id.dayEditImgBtnBottomTab01Catetory01);
		}else if(categotyID ==2 ){
			imgCategory = (ImageButton)bottom01Act.findViewById(R.id.dayEditImgBtnBottomTab01Catetory02);
		}else if(categotyID ==3 ){
			imgCategory = (ImageButton)bottom01Act.findViewById(R.id.dayEditImgBtnBottomTab01Catetory03);
		}else if(categotyID ==4 ){
			imgCategory = (ImageButton)bottom01Act.findViewById(R.id.dayEditImgBtnBottomTab01Catetory04);
		}
		if(categotyID !=0)
		 imgCategory.setBackgroundDrawable(getResources().getDrawable(R.drawable.dayedit_picture_shape_select));
		
		
		wBottom02 = mLocalActivityManager.startActivity( "wBottom02", new Intent(this,DayEditViewBottom02Activity.class));
		
		topFrameContent.addView(wTop01.getDecorView(), new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
		bottomFrameContent.addView( wBottom01.getDecorView(), new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
		
		
		
		// write tab
		final ImageButton dayEditBtnTab1 =  (ImageButton)findViewById(R.id.dayEditBtnTab1);
		dayEditBtnTab1.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if(tabIdx !=0){
					
					if(tabIdx==1){
						
						((FrameLayout) findViewById(R.id.dayEditFrameTop)).removeView(wTop02.getDecorView());
						((FrameLayout) findViewById(R.id.dayEditFrameTop)).addView( wTop01.getDecorView(), new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
						
						((FrameLayout) findViewById(R.id.dayEditFrameBottom)).removeView(wBottom02.getDecorView());
						((FrameLayout) findViewById(R.id.dayEditFrameBottom)).addView( wBottom01.getDecorView(), new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
						
						LinearLayout picLinear =  (LinearLayout)findViewById(R.id.dayEditLinearPicture);
						
						picLinear.setVisibility(View.INVISIBLE);
						
						ImageButton dayEditBtnTab2 =  (ImageButton)findViewById(R.id.dayEditBtnTab2);
						dayEditBtnTab2.setImageDrawable(getResources().getDrawable(R.drawable.edit_tab_picture_btn_50x36));
						
						((ImageButton)v).setImageDrawable(getResources().getDrawable(R.drawable.edit_tab_write_btn_select_50x36));
						
					}
				}
				tabIdx=0;
			}
		});
		
		final ImageButton dayEditBtnTab2 =  (ImageButton)findViewById(R.id.dayEditBtnTab2);
		dayEditBtnTab2.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				
				if(tabIdx !=1){ //자기 자신이 아니고
					if(tabIdx==0){ // 선택된게 tab 1 이면
						
						((FrameLayout) findViewById(R.id.dayEditFrameTop)).removeView(wTop01.getDecorView());
						((FrameLayout) findViewById(R.id.dayEditFrameTop)).addView( wTop02.getDecorView(), new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
						
						((FrameLayout) findViewById(R.id.dayEditFrameBottom)).removeView(wBottom01.getDecorView());
						((FrameLayout) findViewById(R.id.dayEditFrameBottom)).addView( wBottom02.getDecorView(), new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
						
						ImageButton dayEditBtnTab1 =  (ImageButton)findViewById(R.id.dayEditBtnTab1);
						dayEditBtnTab1.setImageDrawable(getResources().getDrawable(R.drawable.edit_tab_write_btn_50x36));
						
						((ImageButton)v).setImageDrawable(getResources().getDrawable(R.drawable.edit_tab_picture_btn_select_50x36));
						
						InputMethodManager imMgr = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
						imMgr.hideSoftInputFromWindow(((EditText)(((DayEditViewTop01Activity)mLocalActivityManager.getActivity( "wTop01")).findViewById(R.id.dayEditText01))).getWindowToken(),0);
					}
				}
				tabIdx=1;
			}
		});
		
		final ImageButton dayEditBtnCancle =  (ImageButton)findViewById(R.id.dayEditBtnCancle);
		dayEditBtnCancle.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if(memoID != 0){
					Intent in = new Intent(DayEditActivity.this,DayActivity.class);
					in.putExtra("memo_id", memoID);
					startActivity(in);
				}
				finish();
				
			}
		});
		
		
		// save button
		final ImageButton dayEditBtnSave =  (ImageButton)findViewById(R.id.dayEditBtnSave);
		dayEditBtnSave.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {				
				
				//content insert update
				if(categotyID ==0){
					Toast.makeText(DayEditActivity.this,"category 선택하세요",Toast.LENGTH_SHORT).show();
					
				}else{
					
					if(memoID ==0){
						memoID = db.insertMemo(categotyID 
								 ,((EditText)(((DayEditViewTop01Activity)mLocalActivityManager.getActivity( "wTop01")).findViewById(R.id.dayEditText01))).getText().toString()) ;
					}else{
						db.updateMemo(categotyID , memoID 
								, ((EditText)(((DayEditViewTop01Activity)mLocalActivityManager.getActivity( "wTop01")).findViewById(R.id.dayEditText01))).getText().toString()) ;
						
					}
					
					Log.d("day edit memoID==================", ""+memoID);
					
					
					Iterator<ImageButton> iterVal = top2DayImgsMap.values().iterator();
					DayImage imgTo=null;
					while (iterVal.hasNext()) {
						ImageButton item = iterVal.next();
						
						if(item.getTag() !=null){
							imgTo=(DayImage)item.getTag();
							if(imgTo.status.equals("INSERT")){
								db.insertMemoMedia(memoID,1,imgTo.imgPath);
							}else if(imgTo.status.equals("UPDATE")){
								db.updateMemoMedia(imgTo.imgSeq, 1,imgTo.imgPath);
							}
						}
					}
					Intent in = new Intent(DayEditActivity.this,DayActivity.class);
					in.putExtra("memo_id", memoID);
					startActivity(in);
					
					finish();
				}
			}
		});
		
		// local picture view cancel
		final ImageButton dayEditBtnPicCancle =  (ImageButton)findViewById(R.id.dayEditBtnPicCancle);
		dayEditBtnPicCancle.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				
				LinearLayout picLinear =  (LinearLayout)parentActivity.findViewById(R.id.dayEditLinearPicture);
				
				picLinear.setVisibility(View.INVISIBLE);
			}
		});
		
		// local device picture preview
		final Button dayEditBtnPicPre =  (Button)findViewById(R.id.dayEditBtnPicPre);
		dayEditBtnPicPre.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				
				localDeicePictureView("PRE");
				
			}
		});
		
		// local device picture Next
		final Button dayEditBtnPicNext =  (Button)findViewById(R.id.dayEditBtnPicNext);
		dayEditBtnPicNext.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				
				
				localDeicePictureView("NEXT");
				
			}
		});
		
		
		// local device picture select 
		final ImageButton dayEditBtnPicView =  (ImageButton)findViewById(R.id.dayEditBtnPicView);
		dayEditBtnPicView.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				
				if(dayImgCnt == 8 && selectImgCnt == 0){ // 8개고 선택된 이미지가 없을때
					Toast.makeText(DayEditActivity.this,"8개 까지~",Toast.LENGTH_SHORT).show();
				}else{
					
					ImageButton pictureView=null;
					
					
					if(selectImgCnt==0){// insert
						
						pictureView=top2DayImgsMap.get(dayImgCnt);
						
						DayImage item = new DayImage(0,Constants.LOCAL_DEVICE_IMAGE_LIST.get(curentImgPositon),"INSERT");
						pictureView.setTag(item);
						dayImgCnt++;
						selectImgCnt=0;
						
					}else{ // update
						// 선택된 이미지와 테두리 변경
						pictureView=top2DayImgsMap.get(selectImgCnt-1);
						LinearLayout linear=(LinearLayout)pictureView.getParent();
						linear.setBackgroundDrawable(getResources().getDrawable(R.drawable.dayedit_picture_shape));
						
						DayImage selectDayImage = (DayImage)pictureView.getTag();
						selectDayImage.setImgPath(Constants.LOCAL_DEVICE_IMAGE_LIST.get(curentImgPositon));
						selectImgCnt=0;
					}
					
					BitmapFactory.Options bitmpaOption = new BitmapFactory.Options();
					Bitmap bitmap = BitmapFactory.decodeFile(Constants.LOCAL_DEVICE_IMAGE_LIST.get(curentImgPositon), bitmpaOption);
					pictureView.setImageBitmap(bitmap);
					
				}
			}
		});
	}
	
	
	
	private void localDeicePictureView(String typePreNext) {
		// local device picture set
		ImageButton localDevicePicView =(ImageButton)findViewById(R.id.dayEditBtnPicView);
		if(typePreNext.endsWith("PRE")) {
			curentImgPositon -- ;
		}
		if(typePreNext.endsWith("NEXT")) {
			curentImgPositon ++; 
		}
		
		BitmapFactory.Options bitmpaOption = new BitmapFactory.Options();
		Bitmap bitmap = BitmapFactory.decodeFile(Constants.LOCAL_DEVICE_IMAGE_LIST.get(curentImgPositon), bitmpaOption);
		
		localDevicePicView.setImageBitmap(bitmap);
		
		
		// preview next visible 
		if( curentImgPositon != 0 && totalImgCnt > 0 ){
			((Button)findViewById(R.id.dayEditBtnPicPre)).setVisibility(View.VISIBLE);
		}else{
			((Button)findViewById(R.id.dayEditBtnPicPre)).setVisibility(View.INVISIBLE);
		}
		
		if( totalImgCnt-1 > curentImgPositon){
			((Button)findViewById(R.id.dayEditBtnPicNext)).setVisibility(View.VISIBLE);
		}else{
			((Button)findViewById(R.id.dayEditBtnPicNext)).setVisibility(View.INVISIBLE);
		}
	}
	
	
}
